import axios from 'axios'
import router from '@/router/index.js'
import { ElMessage } from 'element-plus'

//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000
})

//设置请求拦截器
  request.interceptors.request.use(
    (config) => {
     const login= localStorage.getItem("loginItem")
     if(login){
      config.headers.token=JSON.parse(login).token
     }
      return config
    },
    (error) => { //失败回调

      return Promise.reject(error)
    }
  )

//axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => {//失败回调
    if(error.response.status==401){
      ElMessage.error('请先登录')
      router.push('/login')
    } 
    return Promise.reject(error)
  }
)
export default request